package com.vincce.sport.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.vincce.sport.entity.Activity;
import com.vincce.sport.entity.Advert;
import com.vincce.sport.entity.CompetitionSeason;
import com.vincce.sport.entity.ImgModel;
import com.vincce.sport.entity.ImgStorage;
import com.vincce.sport.entity.News;
import com.vincce.sport.entity.Team;
import com.vincce.sport.entity.Zone;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.vincce.sport.core.utils.CheckUtil;
import com.vincce.sport.core.utils.SimpleStorageClient;
import com.vincce.sport.core.utils.SimpleStorageClient.StorageResult;
import com.vincce.sport.entity.Page;
import com.vincce.sport.mapper.ActivityMapper;
import com.vincce.sport.mapper.AdvertMapper;
import com.vincce.sport.mapper.CompetitionSeasonMapper;
import com.vincce.sport.mapper.ImgModelMapper;
import com.vincce.sport.mapper.ImgStorageMapper;
import com.vincce.sport.mapper.NewsMapper;
import com.vincce.sport.mapper.SchoolMapper;
import com.vincce.sport.mapper.TeamMapper;
import com.vincce.sport.mapper.ZoneMapper;


@Controller
@RequestMapping("/tnews")
public class NewsController extends BaseController{
	@Resource
	private NewsMapper newsmapper;
	@Resource
	private TeamMapper teamMapper;
	@Resource
	private ZoneMapper zoneMapper;
	@Resource
	private ActivityMapper activityMapper;
	@Resource
	private ImgModelMapper imgModelMapper;
	@Resource
	private ImgStorageMapper imgStorageMapper;
	@Resource
	private AdvertMapper advertMapper;
	@Resource
	private SchoolMapper schoolMapper;

    @RequestMapping("/list")
    public String newsList(Model model, News news, Page<News> page,String schoolId) throws IOException{
        Map<String, Object> filter = new HashMap<String, Object>();
        if(news.getTitle() != null && !news.getTitle().equals("")){
            filter.put("title", news.getTitle());
        }
		if(news.getContent() != null && !news.getContent().equals("")){
			filter.put("content", news.getContent());
		}
		if(news.getTeamId() != null && !news.getTeamId().equals("")){
			filter.put("teamId", news.getTeamId());
		}
		if(news.getStatus() != null && !news.getStatus().equals("")){
			filter.put("status", news.getStatus());
		}
		if(schoolId != null && !schoolId.equals("")){
			if(news.getTeamId() != null && !news.getTeamId().equals("")){
				
			}else{
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("schoolId", schoolId);			
				List<Team> teamList=teamMapper.queryTeamBySchoolId(map);
				String ids="";
				for(int i=0;i<teamList.size();i++){
					Integer id=teamList.get(i).getId();
					if(i+1==teamList.size()){
						ids+=id;
					}else{
						ids+=id+",";
					}					
				}
				String[] strId =ids.split(",");
	            Integer[] intId = new Integer[strId.length];
	            for(int i = 0;i<strId.length;i++){
	            	intId[i] = Integer.parseInt(strId[i]);
	            }
				filter.put("teamIds", intId);
			}			
		}
        page.setFilter(filter);

        page.setResult(replace(newsmapper.queryNewsList(page)));
        page.setTotal(newsmapper.queryNewsCount(page.getFilter()));
        model.addAttribute("page",page);  
        model.addAttribute("news",news);
        model.addAttribute("schoolList",schoolMapper.queryBySchoolAll());
//        model.addAttribute("teamList",teamMapper.queryTeamByAll());
        model.addAttribute("schoolId",schoolId);  
        return "backstage/newsList";
    }
    /**
	 * 图片路径替换
	 * @param imgStorageList
	 * @return
	 */
	public List<News> replace(List<News> newsList){
		if(newsList!=null && newsList.size()>0){
			for(News news:newsList){
				if(!CheckUtil.isEmpty(news.getNewsImg())){
					news.setNewsImg(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+news.getNewsImg(), "ori"));
					news.setSpecialistImg(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+news.getSpecialistImg(), "ori"));
				}
				
			}
		}
		return newsList;
	}
    @RequestMapping("/addOrUpdate")
    @ResponseBody
    public String addOrUpdateNews(Model model, News news, HttpServletRequest request) throws IOException{
    	Map<String, Object> result = new HashMap<String, Object>();
    	// 转型为MultipartHttpRequest：
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 获得文件：     
        MultipartFile file = multipartRequest.getFile("file");
        MultipartFile file1 = multipartRequest.getFile("file1");
        StorageResult obj = new StorageResult(200, "");
        Long count = 0l;
        news.setUpdateUser(getCurrentUser().getId().intValue());
    	news.setUpdateTime(new Date());
    	
        if(CheckUtil.isEmpty(news.getId())){
        	if (file != null && !file.isEmpty()) {
        		String fileName = file.getOriginalFilename();
            	String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
            	
            	if (!fileType.equals(".jpg") && !fileType.equals(".JPG") && !fileType.equals(".png") && !fileType.equals(".PNG")) {
            		result.put("msg", "格式不正确,只支持后缀名为.jpg或者.png的图片上传。");
            		result.put("suc", false);
            		return JSON.toJSONString(result);
    			}else{
    				
    				 obj = SimpleStorageClient.upload(2, file.getInputStream(), fileType);
    				
    				 if (obj.statusCode == 200) {
    					    String path= obj.info.replaceAll("\\\\", "/");
    					    news.setNewsImg(path);
    				 }
    			}
        	}
        	if (file1 != null && !file1.isEmpty()) {
        		String fileName = file1.getOriginalFilename();
            	String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
            	
            	if (!fileType.equals(".jpg") && !fileType.equals(".JPG") && !fileType.equals(".png") && !fileType.equals(".PNG")) {
            		result.put("msg", "格式不正确,只支持后缀名为.jpg或者.png的图片上传。");
            		result.put("suc", false);
            		return JSON.toJSONString(result);
    			}else{
    				
    				 obj = SimpleStorageClient.upload(2, file1.getInputStream(), fileType);
    				
    				 if (obj.statusCode == 200) {
    					    String path= obj.info.replaceAll("\\\\", "/");
    					    news.setSpecialistImg(path);
    				 }
    			}
        	}
        	news.setCreateTime(new Date());
        	news.setCreateUser(getCurrentUser().getId().intValue());        	
        	count = newsmapper.insertNews(news);
        } else{	
        	if (file != null && !file.isEmpty()) {
        		String fileName = file.getOriginalFilename();
            	String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
            	
            	if (!fileType.equals(".jpg") && !fileType.equals(".JPG") && !fileType.equals(".png") && !fileType.equals(".PNG")) {
            		result.put("msg", "格式不正确,只支持后缀名为.jpg或者.png的图片上传。");
            		result.put("suc", false);
                    return JSON.toJSONString(result);
    			}else{
    				
    				 obj = SimpleStorageClient.upload(2, file.getInputStream(), fileType);
    				
    				 if (obj.statusCode == 200) {
    					    String path= obj.info.replaceAll("\\\\", "/");
    					    news.setNewsImg(path);
    				 }
    			}
        	}
        	if (file1 != null && !file1.isEmpty()) {
        		String fileName = file1.getOriginalFilename();
            	String fileType = fileName.substring(fileName.lastIndexOf("."), fileName.length());
            	
            	if (!fileType.equals(".jpg") && !fileType.equals(".JPG") && !fileType.equals(".png") && !fileType.equals(".PNG")) {
            		result.put("msg", "格式不正确,只支持后缀名为.jpg或者.png的图片上传。");
            		result.put("suc", false);
                    return JSON.toJSONString(result);
    			}else{
    				
    				 obj = SimpleStorageClient.upload(2, file1.getInputStream(), fileType);
    				
    				 if (obj.statusCode == 200) {
    					    String path= obj.info.replaceAll("\\\\", "/");
    					    news.setSpecialistImg(path);
    				 }
    			}
        	}
        	count = newsmapper.updateNews(news);
        }       
        result.put("suc", count > 0 ? true : false);
        return JSON.toJSONString(result);
    }

    @RequestMapping("/delete")
    @ResponseBody
    public String deleteTNews(Model model, Long id, HttpServletRequest request) throws IOException{
        Boolean flag = false;
        newsmapper.deleteById(id);
        flag = true;
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("obj", flag);
        return JSON.toJSONString(result);
    }

    @RequestMapping("/getById")
    public String getById(Model model, Long id, HttpServletRequest request) throws IOException{
    	News news;
    	if(CheckUtil.isEmpty(id)){
    		news=new News();
    	}else{
    		news=newsmapper.findNewsById(id);
    	}
    	 
    	model.addAttribute("tnews",news);
    	model.addAttribute("teamList",teamMapper.queryTeamByAll());
        return "backstage/newsForm";
    }
    /**
     * 檢查新闻标题是否已存在
     * @param title
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping("/checkTNewsTitle")
    @ResponseBody
    public String checkTNewsTitle(String title,Long id) throws Exception{
        News news =new News();
        if(title != null && !title.equals("")){
        	news.setTitle(title);
        }
        if(id!= null && !id.equals("")){
        	news.setId(id);
        }
        Integer fg = 0;
        List<News> newsList = newsmapper.findNewsByOne(news);
        if(newsList!=null && newsList.size()>0){
        	fg = 1;
        }
        return Boolean.toString(fg==0);
    }
    
    
    //------------------------------前台展示------------------------------------//
    @RequestMapping("/newsWebList")
    public String newsWebList(Model model, News news,Long zoneId,Long cityId,Long schoolId) throws IOException{
    	Page<News> remarkNewsPage=new Page<News>();
    	List<News> newsList=new ArrayList<News>();
		Map<String, Object> filter = new HashMap<String, Object>();	
    	//专家点评
        filter=new HashMap<String, Object>();
//        if(news.getTeamId() != null && !news.getTeamId().equals("")){
//        	filter.put("teamId", news.getTeamId());
//        }
		filter.put("status", 1);
		filter.put("type", 1);
		remarkNewsPage.setFilter(filter);
		remarkNewsPage.setLimit(3);
		remarkNewsPage.setResult(replace(newsmapper.queryNewsList(remarkNewsPage)));
        model.addAttribute("remarkNewsPage",remarkNewsPage);
        //新闻列表
	    news.setStatus(1);   
	    newsList=replace(newsmapper.findAllNews(news));  
	    List<News> newsList2=new ArrayList<News>();
	    List<News> newsList3=new ArrayList<News>();
	    List<News> newsList4=new ArrayList<News>();
	    if(newsList!=null && newsList.size()>0){
	    	for(int i=0;i<newsList.size();i++){
	    		if(newsList.get(i).getType()==2){
	    			newsList2.add(newsList.get(i));
	    		}
	    		if(newsList.get(i).getType()==3){
	    			newsList3.add(newsList.get(i));
	    		}
				if(newsList.get(i).getType()==4){
					newsList4.add(newsList.get(i));
				}
	    	}
	    }
        model.addAttribute("newsList2",newsList2); 
        model.addAttribute("newsList3",newsList3);  
        model.addAttribute("newsList4",newsList4);  
        model.addAttribute("news",news);
        //赛区
        List<Zone> zoneList=new ArrayList<Zone>();   
        zoneList=zoneMapper.queryByZoneAll();
        model.addAttribute("zoneList",zoneList);
        //活动专区   
//        Page<Activity> page=new Page<Activity>();
//        Map<String, Object> filter2 = new HashMap<String, Object>();		
//	    filter2.put("status", 2);	   
//		page.setFilter(filter2);
//		remarkNewsPage.setLimit(2);
//		page.setResult(replaceActivity(activityMapper.queryActivityByPage(page)));
//		model.addAttribute("activityPage",page);
        //新闻精彩图集
        Map<String, Object> filter4 = new HashMap<String, Object>();
        Page<Advert> page4=new Page<Advert>();
	    filter4.put("name", "新闻精彩图集");
	    filter4.put("status", 1);
	    page4.setLimit(1);
	    page4.setFilter(filter4);
	    page4.setResult(advertMapper.queryAdvertList(page4));
		//精彩图库		
		Map<String, Object> filter3 = new HashMap<String, Object>();
		Page<ImgModel> page3=new Page<ImgModel>();
		filter3.put("status", 1);
        page3.setFilter(filter3);
        page3.setLimit(4);
        page3.setResult(imgModelMapper.queryImgModelList(page3));
        if(page3!=null && page3.getResult().size()>0){
        	Long modelId=page3.getResult().get(0).getId();
        	ImgStorage imgStorage = new ImgStorage();			
			imgStorage.setModelId(modelId);
//			List<ImgStorage> imgStorageList = imgStorageMapper.findImgStorageByOne(imgStorage);
//			if(imgStorageList!=null && imgStorageList.size()>0){
				String imgPath=page4.getResult().get(0).getAdvertImg();
				page3.getResult().get(0).setImgPath(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+imgPath, "ori"));
//			}
        }
        model.addAttribute("imgModelPage",page3);
        //新闻列表广告位
        Page<Advert> advertPage=new Page<Advert>();
	    filter=new HashMap<String, Object>();	
	    filter.put("name", "新闻列表");
	    filter.put("status", 1);
	    advertPage.setLimit(1);
	    advertPage.setFilter(filter);
	    advertPage.setResult(replaceAdvert(advertMapper.queryAdvertList(advertPage)));
	    model.addAttribute("advertPage",advertPage);
	    
        
        model.addAttribute("zoneId",zoneId); 
        model.addAttribute("cityId",cityId);  
        model.addAttribute("schoolId",schoolId);  
        model.addAttribute("teamId",news.getTeamId());
        return "foreground/news";
    }
    
    @RequestMapping("/newsWebDetail")
    public String newsWebDetail(Model model, Long id, HttpServletRequest request) throws IOException{
    	News news;
    	if(CheckUtil.isEmpty(id)){
    		news=new News();
    	}else{
    		news=newsmapper.findNewsById(id);
    		news.setNewsImg(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+news.getNewsImg(), "ori"));
    	}   	 
    	model.addAttribute("newsDetail",news);
    	Page<News> remarkNewsPage=new Page<News>();
    	Map<String, Object> filter = new HashMap<String, Object>();	
    	//专家点评
        filter=new HashMap<String, Object>();
        if(news.getTeamId() != null && !news.getTeamId().equals("")){
//        	filter.put("teamId", news.getTeamId());
        }
		filter.put("status", 1);
		filter.put("type", 1);
		remarkNewsPage.setFilter(filter);
		remarkNewsPage.setLimit(3);
		remarkNewsPage.setResult(replace(newsmapper.queryNewsList(remarkNewsPage)));
        model.addAttribute("remarkNewsPage",remarkNewsPage);
        //新闻精彩图集
        Map<String, Object> filter4 = new HashMap<String, Object>();
        Page<Advert> page4=new Page<Advert>();
	    filter4.put("name", "新闻精彩图集");
	    filter4.put("status", 1);
	    page4.setLimit(1);
	    page4.setFilter(filter4);
	    page4.setResult(advertMapper.queryAdvertList(page4));
    	//精彩图库		
		Map<String, Object> filter3 = new HashMap<String, Object>();
		Page<ImgModel> page3=new Page<ImgModel>();
		filter3.put("status", 1);
        page3.setFilter(filter3);
        page3.setLimit(4);
        page3.setResult(imgModelMapper.queryImgModelList(page3));
        if(page3!=null && page3.getResult().size()>0){
        	Long modelId=page3.getResult().get(0).getId();
        	ImgStorage imgStorage = new ImgStorage();			
			imgStorage.setModelId(modelId);
//			List<ImgStorage> imgStorageList = imgStorageMapper.findImgStorageByOne(imgStorage);
//			if(imgStorageList!=null && imgStorageList.size()>0){
				String imgPath=page4.getResult().get(0).getAdvertImg();
				page3.getResult().get(0).setImgPath(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+imgPath, "ori"));
//			}
        }
        model.addAttribute("imgModelPage",page3);
        
        //新闻详情广告位
        Page<Advert> advertPage=new Page<Advert>();
	    filter=new HashMap<String, Object>();	
	    filter.put("name", "新闻详情");
	    filter.put("status", 1);
	    advertPage.setLimit(1);
	    advertPage.setFilter(filter);
	    advertPage.setResult(replaceAdvert(advertMapper.queryAdvertList(advertPage)));
	    model.addAttribute("advertPage",advertPage);
        return "foreground/newsDetail";
    }
    /**
	 * 图片路径替换
	 * @param imgStorageList
	 * @return
	 */
	public List<Activity> replaceActivity(List<Activity> activityList){
		if(activityList!=null && activityList.size()>0){
			for(Activity activity:activityList){
				if(!CheckUtil.isEmpty(activity.getImgPath())){
					activity.setImgPath(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+activity.getImgPath(), "ori"));
				}
				
			}
		}
		return activityList;
	}
	
	/**
	 * 图片路径替换
	 * @param imgStorageList
	 * @return
	 */
	public List<Advert> replaceAdvert(List<Advert> advertList){
		if(advertList!=null && advertList.size()>0){
			for(Advert adv:advertList){
				adv.setAdvertImg(String.format(SimpleStorageClient.REQUEST_URI2_PREFIX+adv.getAdvertImg(), "ori"));
			}
		}
		return advertList;
	}
}
